import {ref, watch} from "vue"
import globalSettingStore from "@/store/globalSettingStore";
import {ElMessage} from "element-plus";
export interface TimerOption{
    // 倒计时
    countDown:number
    // 倒计时结束回调函数
    callback:()=>void
}
export  default function (){
    // 全局设置 store
    const {globalSetting}=globalSettingStore()
    let time =ref<number>(0)
    let timer:number

    function check(){
        return globalSetting.showSpendTime

    }

    function startTime(timerOption?:TimerOption){
        if(!check()){
            return
        }
        console.log('[ timer ] start')

        if(timerOption){
            time.value=timerOption.countDown
            // 开启倒计时
            timer=setInterval(()=>{
                time.value--
            },1000)
            // 倒计时到零触发回调
            watch(time,(newV)=>{
                if(newV === 0){
                    timerOption.callback()
                }
            })
        }else{
            time.value=0
            timer=setInterval(()=>{
                time.value++
            },1000)
        }
    }
    function stopTime(){

        clearInterval(timer)
        console.log('[ timer ] stop')
    }


    return {
        time,
        startTime,
        stopTime,

    }
}